package com.karina.visualization.chart.skins;

import java.util.List;

import com.karina.visualization.chart.client.Gradient;
import com.karina.visualization.chart.client.Graphics;
import com.karina.visualization.chart.model.CategorizedSeriesModel;
import com.karina.visualization.chart.model.SeriesModel.CategoryValue;

public class ColumnSkin extends BaseSkin<CategorizedSeriesModel> {

	private CategorizedSeriesModel data;

	@Override
	public void setData(CategorizedSeriesModel data) {
		this.data = data;
	}

	@Override
	public CategorizedSeriesModel getData() {
		return data;
	}

	@Override
	public void draw(Graphics graphics) {
		drawColumns(graphics);
	}

	private void drawColumns(Graphics graphics) {

		double x = data.getRelativeX() + data.getMarginLeft() + data.getX();
		double y = data.getY();
		List<CategoryValue> listofData = data.getValue();

		int gap = (graphics.getCoordWidth() - data.getMarginLeft()
				- data.getX() - data.getRight())
				/ listofData.size();

		int width = data.getWidth();
		int height = data.getHeight() - data.getMarginBottom();

		double max = data.getMaxValue();

		Gradient gradient = (Gradient) getStyleDeclaretion().getStyle(
				"backgroundColor");

		// if (color == null) {
		// color = Graphics.PRE_DEFINED_COLOR_ARRAY[data.getIndex()];
		// }

		if (gradient == null) {
			gradient = Graphics.PRE_DEFINED_GRADIENT_ARRAY[data.getIndex()];
		}
		graphics.saveContext();
		graphics.beginPath();

		for (CategoryValue category : listofData) {
			double value = Double.parseDouble(category.getValue().toString());
			double h = (value / max) * height;
			// graphics.moveTo(x, height);
			// graphics.lineTo(width, height -y );
			// graphics.stroke();

			graphics.rect(x, y + (height - h), width, h);
			graphics.fillStyle(x, y + (height - h), x + width, y + height,
					gradient);
			// graphics.shallow(4, 4, 6, 240, 240, 240, 0.4);

			graphics.fillRect((int) x + 1, (int) (y + (height - h) + 1),
					width - 2, (int) h - 2);
			graphics.stroke();
			graphics.fillStyle(0, 0, 0, 1);
			graphics.drawText(x + width / 2, y + (height - h), category
					.getValue().toString(), "center", "bottom");
			x += gap;
		}

		graphics.endPath();
		graphics.restoreContext();
	}

	@Override
	public void cleanup(Graphics graphics) {
		// graphics.clear();
	}

	@Override
	public void refresh(Graphics graphics) {

	}

}
